import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:url_launcher/url_launcher.dart';
// import 'dart:async';

import 'package:webview_flutter/webview_flutter.dart';

class JYZPayPage extends StatefulWidget {
  String url;
  String name;
  JYZPayPage({Key key, this.url, this.name}) : super(key: key);

  @override
  _JYZPayPageState createState() => _JYZPayPageState(url);
}

class _JYZPayPageState extends State<JYZPayPage> {
  String url;
  _JYZPayPageState(this.url);
  WebViewController _controller;
// final flutterWebviewPlugin = new FlutterWebviewPlugin();
FlutterWebviewPlugin plugin = new FlutterWebviewPlugin();
// MethodChannel channel=MethodChannel("flutter_webview_plugin");

@override
void initState() { 
  super.initState();
 plugin.onUrlChanged.listen((String value) {

      if (value.startsWith('alipays://') || value.startsWith('alipay://')) {
        //   print('blocking navigation to $request}');
        _openApp(value);
        // 
        setState(() {
          // plugin.goBack();
          plugin.stopLoading();
          plugin.reload();
        });
      }
      if (value.startsWith('weixin://')) {
        //   print('blocking navigation to $request}');
        _openApp(value);
        setState(() {
          plugin.goBack();
        });
      }
    });
}
  @override
  Widget build(BuildContext context) {
    return new WebviewScaffold(
      url: url,
// 登录的URL
      appBar: new AppBar(
        title:Text(widget.name),
        iconTheme: new IconThemeData(color: Colors.white),
        actions: <Widget>[
                  // new IconButton(
                  //     icon: new Icon(Icons.arrow_left),
                  //     onPressed: () {
                  //       _controller.goBack();
                  //     }),
                  new IconButton(
                      icon: new Icon(Icons.home),
                      onPressed: () {
                        _controller.loadUrl(url);
                      })
                ]
      ),
    );
  }

  void _openApp(openurl) async {
    // Android
    print("open app");
    final url = 'vnd.' + openurl;
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      //  Ios
      final url = openurl;
      if (await canLaunch(url)) {
        await launch(url);
      } else {
        throw 'Could not launch $url';
      }
    }
  }

  void dispose() {
    super.dispose();
  }
}
